<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="学校名称" prop="schoolName">
        <el-input v-model="queryParams.schoolName" placeholder="请输入学校名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学校简称" prop="schoolAliaeName">
        <el-input v-model="queryParams.schoolAliaeName" placeholder="请输入学校简称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属代理" prop="agentName">
        <el-input v-model="queryParams.agentName" placeholder="请输入所属代理" @click.native="openSelectAgent(1)" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="tel">
        <el-input v-model="queryParams.tel" placeholder="请输入联系电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input v-model="queryParams.contacts" placeholder="请输入联系人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="省、市、区" prop="queryProvinceAndCityAndDistrict">
        <el-cascader placeholder="请选择省、市、区" v-model="queryParams.queryProvinceAndCityAndDistrict" :options="options"
          @keyup.enter.native="handleQuery" @lazy-load="selectLoadOptions"
          :props="{ lazy: true,checkStrictly:true,multiple: true, lazyLoad: selectLoadOptions,value:'regionId',label:'regionName' }"
          clearable></el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.school_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['school:schoolinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['school:schoolinfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['school:schoolinfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['school:schoolinfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schoolinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="20" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="学校全称" align="center" prop="schoolName" />
      <el-table-column label="学校简称" align="center" prop="schoolAliaeName" />
      <el-table-column label="代理" align="center" prop="agentName" />
      <el-table-column label="招生人数" align="center" prop="studentCapacity" />
      <el-table-column label="学校类型" align="center" prop="schoolType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.school_type" :value="scope.row.schoolType" />
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="tel" />
      <el-table-column label="大屏数" align="center" prop="bindDeviceNum" />

      <el-table-column label="省、市、区" align="center" prop="provinceAndCityAndDistrict" />
      <el-table-column label="签约日期" align="center" prop="signArray" width="180">
        <template slot-scope="scope">
          {{scope.row.signArray[0]}}～{{scope.row.signArray[1]}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.school_state" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column width="200" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['school:schoolinfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['school:schoolinfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改学校管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学校全称" prop="schoolName">
              <el-input v-model="form.schoolName" placeholder="请输入学校名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学校简称" prop="schoolAliaeName">
              <el-input v-model="form.schoolAliaeName" placeholder="请输入学校简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学校类型" prop="schoolType">
              <el-select v-model="form.schoolType" placeholder="请选择" clearable @change="handleSchoolTypeChange">
                <el-option v-for="dict in dict.type.school_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属代理" prop="agentName">
              <el-input v-model="form.agentName" placeholder="请输入所属代理" @click.native="openSelectAgent(2)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话(登录账号)" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="大屏数" prop="bindDeviceNum">
              <el-input-number v-model="form.bindDeviceNum" min="0" placeholder="学校可绑定多少个大屏" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省、市、区" prop="provinceAndCityAndDistrict">
              <el-cascader placeholder="请选择省、市、区" style="width: 100%" v-model="form.provinceAndCityAndDistrict"
                :options="options" @lazy-load="selectLoadOptions"
                :props="{ lazy: true, lazyLoad: selectLoadOptions,value:'regionId',label:'regionName' }"
                clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成立日期" prop="establishedDate">
              <el-date-picker clearable v-model="form.establishedDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择成立日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约日期" prop="signArray">
              <el-date-picker clearable type="daterange" format="yyyy-MM-dd" v-model="form.signArray"
                value-format="yyyy-MM-dd" placeholder="请选择签约日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="一销负责人" prop="firstSaleUser">
              <el-input v-model="form.firstSaleUser" placeholder="请输入一销负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二销负责人" prop="secondSaleUser">
              <el-input v-model="form.secondSaleUser" placeholder="请输入二销负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择">
                <el-option v-for="dict in dict.type.school_state" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="年参考价" prop="referencePrice">
              <el-input v-model="form.referencePrice" placeholder="请输入年参考价">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="佣金类型" prop="feeType">
              <el-select v-model="form.feeType" placeholder="佣金类型" @change="selectChangeFeeType">
                <el-option v-for="dict in dict.type.school_fee_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年佣金比例" prop="ratio" v-if="form.feeType==1">
              <el-select v-model="form.ratio" placeholder="请选择">
                <el-option v-for="dict in dict.type.school_fee_ratio" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年佣金" prop="ratio" v-if="form.feeType==2">
              <el-input v-model="form.ratio" placeholder="请输入佣金">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备课类型" prop="orgType">
              <el-radio-group v-model="form.orgType" size="medium">
                <el-radio-button v-for="dict in dict.type.org_type" :key="dict.value"
                  :label="dict.value">{{dict.label}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程级别" prop="level">
              <el-checkbox-group v-model="form.level" size="medium">
                <el-checkbox-button v-for="dict in dict.type.level" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="介绍" prop="introduce">
              <el-input v-model="form.introduce" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          {{ submitLoading ? '提交中...' : '确定' }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择代理 -->
    <SelectAgent ref="selectAgent" :open="selectFlag" @selected-data="selectAgentData"
      @close-select-window="closeSelectAgent" />
  </div>
</template>

<script>
  import {
    listSchoolinfo,
    getSchoolinfo,
    delSchoolinfo,
    addSchoolinfo,
    updateSchoolinfo
  } from "@/api/bus_web/school/schoolinfo";
  import {
    loadOptions
  } from "@/api/system/sys_region";
  import {
    isEmpty
  } from "@/utils/validate"
  import {
    isNumberStr
  } from '@/utils/index'
  import SelectAgent from "../../agent/agent/select.vue"
  import {
    mapState
  } from 'vuex';
  import store from "@/store";
  export default {
    name: "Schoolinfo",
    dicts: ['school_state', 'common_state', 'level_of_education', 'school_type', 'level', 'org_type', 'school_fee_type',
      'school_fee_ratio'
    ],
    components: {
      SelectAgent
    },
    data() {
      return {
        options: [],
        // 是否显示代理选择
        selectFlag: false,
        submitLoading: false,
        //选中代理
        selectedAgentData: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 学校管理表格数据
        schoolinfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          schoolName: null,
          schoolAliaeName: null,
          agentId: null,
          agentIdArray: [],
          agentName: null,
          schoolType: null,
          levelOfEducation: null,
          tel: null,
          introduce: null,
          province: null,
          city: null,
          district: null,
          address: null,
          state: null,
          queryProvinceAndCityAndDistrict: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          state: [{
            required: true,
            message: "上线不能为空",
            trigger: "change"
          }],
          provinceAndCityAndDistrict: [{
            required: true,
            message: "省、市、区不能为空",
            trigger: "blur"
          }],
          schoolType: [{
            required: true,
            message: "学校类型不能为空",
            trigger: "change"
          }],
          schoolName: [{
            required: true,
            message: "学校全称不能为空",
            trigger: "change"
          }],
          schoolAliaeName: [{
            required: true,
            message: "学校简称不能为空",
            trigger: "change"
          }],
          agentName: [{
            required: true,
            message: "所属代理不能为空",
            trigger: ["change", "blur"]
          }],
          studentCapacity: [{
            required: true,
            message: "招生人数不能为空",
            trigger: "change"
          }],
          tel: [{
            required: true,
            message: "联系电话不能为空",
            trigger: "blur"
          }],
          bindDeviceNum: [{
            required: true,
            message: "大屏数不能为空",
            trigger: "blur"
          }],
          contacts: [{
            required: true,
            message: "联系人不能为空",
            trigger: "blur"
          }],
          level: [{
            required: true,
            message: "级别不能为空",
            trigger: "change"
          }],
          orgType: [{
            required: true,
            message: "备课类型不能为空",
            trigger: "change"
          }],
          signArray: [{
            required: true,
            message: "签约日期不能为空",
            trigger: ["change", "blur"]
          }],
          feeType: [{
            required: true,
            message: "佣金类型不能为空",
            trigger: ["change", "blur"]
          }],
          ratio: [{
            required: true,
            validator: (rule, value, callback) => {
              if (isEmpty(value)) {
                callback(new Error('佣金/佣金比例必须为空'));
              } else if (!isEmpty(value) && !isNumberStr(value)) {
                callback(new Error('佣金/佣金比例必须为数字'));
              } else {
                callback();
              }
            },
            trigger: ["change", "blur"]
          }],
          referencePrice: [{
            required: true,
            validator: (rule, value, callback) => {
              if (isEmpty(value)) {
                callback(new Error('参考价不能为空'));
              } else if (!isEmpty(value) && !isNumberStr(value)) {
                callback(new Error('参考价必须为数字'));
              } else {
                callback();
              }
            },
            trigger: ["change", "blur"]
          }]
        }
      };
    },
    created() {
      this.getList();
    },
    computed: {
      ...mapState({
        agent: state => state.selectAgent.agent,
        agentSelectModel: state => state.selectAgent.agentSelectModel
      })
    },
    methods: {
      /**省 市 区*/
      selectLoadOptions(node, resolve) {
        var query = {
          regionLevel: node.level + 1,
          parentId: node.value || null
        }
        loadOptions(query).then(response => {
          resolve(response.data);
        });
      },
      /** 查询学校管理列表 */
      getList() {
        this.loading = true;
        listSchoolinfo(this.queryParams).then(response => {
          this.schoolinfoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          contacts: null,
          schoolName: null,
          schoolAliaeName: null,
          agentId: null,
          agentName: null,
          studentCapacity: null,
          schoolType: null,
          levelOfEducation: null,
          tel: null,
          introduce: null,
          province: null,
          city: null,
          district: null,
          address: null,
          establishedDate: null,
          state: null,
          gmtCreate: null,
          gmtModify: null,
          deleted: null,
          createBy: null,
          updateBy: null,
          stuCount: null,
          referencePrice: null,
          secondSaleUser: null,
          firstSaleUser: null,
          ratio: null,
          bookCount: null,
          level: [],
          orgType: null,
          signArray: [],
          signDate: null,
          signDateEnd: null,
          feeType: null,
          bindDeviceNum: null
        };
        this.resetForm("form");
        this.submitLoading = false
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.orgId = null
        this.queryParams.orgIdArray = []
        this.queryParams.agentIdArray = []
        this.handleQuery();

      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleSchoolTypeChange(value) {

        if (value == 50) {
          this.form.bindDeviceNum = 2
        } else if (value == 100) {
          this.form.bindDeviceNum = 1
        } else if (value == 400) {
          this.form.bindDeviceNum = 4
        }

      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加学校管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getSchoolinfo(id).then(response => {
          this.form = response.data
          this.open = true;
          this.title = "修改学校管理";
        });
      },
      /** 选择佣金类型 */
      selectChangeFeeType(value) {
        this.form.ratio = null
      },
      /** 提交按钮 */
      submitForm() {
        this.submitLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.studentCapacity = this.form.schoolType
            if (this.form.signArray.length > 0) {
              this.form.signDate = this.form.signArray[0]
              this.form.signDateEnd = this.form.signArray[1]
            }
            if (this.form.id != null) {
              updateSchoolinfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addSchoolinfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            this.submitLoading = false
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除学校管理编号为"' + ids + '"的数据项？').then(function() {
          return delSchoolinfo(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('school/schoolinfo/export', {
          ...this.queryParams
        }, `学校列表_${new Date().getTime()}.xlsx`)
      },
      //选择代理
      openSelectAgent(selectVal) {
        this.selectFlag = true
        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectAgent/cleanAgent')
        this.$store.dispatch('selectAgent/setAgentSelectModel', selectVal)
      },
      closeSelectAgent() {
        this.selectFlag = false
      },
      //确定代理
      selectAgentData() {
        this.closeSelectAgent()
        if (this.agentSelectModel == 2) {
          this.$set(this.form, 'agentName', this.agent[0].agentName)
          this.$set(this.form, 'agentId', this.agent[0].id)
          this.$refs.form.clearValidate(['agentName'])
        } else {
          this.queryParams.agentName = this.agent.map(item => item.agentName).join(',')
          this.queryParams.agentIdArray = this.agent.map(item => item.id)
        }
        this.$store.dispatch('selectAgent/cleanAgent')
      },
      //分配课程
      handleCourse(row) {

        this.$tab.openPage("分配课程", '/school/schoolinfo/related/course/' + row.id)
      }
    }
  };
</script>
<style scoped>
  /* 使用 :deep() 替代 ::v-deep，兼容性更好 */
  :deep(.el-input__inner),
  :deep(.el-input__inner),
  :deep(.el-cascader),
  :deep(.el-cascader .el-input__inner),
  :deep(.el-date-editor),
  :deep(.el-date-editor .el-input__inner),
  :deep(.el-textarea__inner),
  :deep(.el-select .el-input__inner) {
    width: 100% !important;
    box-sizing: border-box;
  }
</style>
